package com.lagou.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {

    //将doGet 作为调度器， 根据 请求功能不同 调用对应的方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取参数
        //String methodName = req.getParameter("methodName");
        String methodName = null;

        // 1. 获取Post  请求的  content-type 类型
        String contentType = req.getHeader("Content-Type");

        //判断传递的诗句是否是JSon格式
        if ("application/json;charset=utf-8".equals(contentType)){
            //是JSON 格式
            String postJSON = getPostJSON(req);

            //将JSON 格是转化为MAP
            Map<String, Object> map = JSON.parseObject(postJSON, Map.class);

            methodName =  (String) map.get("methodName");

            //将获取到的数据, 保存到 request 对象中

            req.setAttribute("map", map);

        }else {
            methodName = req.getParameter("methodName");

        }




        if (methodName != null){
            //反射方法进行判断
            try {
                //获取字节码 this = TextServlet
                Class c =  this.getClass();
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                //调用Method 对象 的invoke 方法
                method.invoke(this,req, resp);


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(" the need you have requested don'T exist ");

            }

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //Post 请求为、该格式， 使用该方法进行读取
    public String getPostJSON( HttpServletRequest request ){


        try {
            //1. 从request 中获取缓冲输入流对象
            BufferedReader reader = request.getReader();

            //2. 创建StringBuffer 保存读取的数据
            StringBuffer sb = new StringBuffer();

            //3. 循环读取
            String line = null;
            while ( (line = reader.readLine() ) != null ){

                //每次读取到的数据追加到StringBuffer
                sb.append(line);

            }


            //4. 返回结果
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }






}
